<template>
  <div class="template-wrapper">
    <div class="template-search">
      <el-button type="primary" @click="addTemplate">新增模板</el-button>
      <el-input clearable placeholder="请输入模板名称" v-model="keyword" @change="onChange">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <!-- <el-table-column
        type="selection"
        width="55"
        align="center"
      /> -->
      <!-- <el-table-column label="模板ID" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.TemplateId }}
        </template>
      </el-table-column> -->
      <el-table-column label="模板名称" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.TemplateName }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="模板类型">
        <template slot-scope="scope">
          <span>{{ scope.row.TemplateType | templateTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人">
        <template slot-scope="scope">
          <span>{{ scope.row.Creator }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="模板合同类型">
        <template slot-scope="scope">
          <span>{{ scope.row.tenantTemplateType | typeFilter }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column class-name="status-col" label="模板状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status || '' }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="CreatedOn" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" style="marginright: 4px" />
          <span>{{ scope.row.CreatedOn | dateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClickInfo(scope.row)">预览</el-button>
          <el-button type="text" size="small" @click="handleClickMod(scope.row)">编辑</el-button>
          <!-- <el-button type="text" size="small" @click="handleClickDelete(scope.row)">删除</el-button> -->
          <!--  v-if="fromPath==='contract'" -->
          <!-- <el-button type="text" size="small" @click="handleClickCreate(scope.row)">发起合同</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="template-page">
      <el-pagination
        small
        layout="prev, pager, next, total, sizes, jumper"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
      >
      </el-pagination>
    </div>

    <!-- 签署方弹框 -->
    <!-- <SignDialog :visible="dialogVisible" @toggle-dialog="toggleDialog" :recipients="recipients" @approvers="createByTemplate"></SignDialog> -->
  </div>
</template>

<script>
import moment from 'moment';
import { getTemplateList } from '@common/api/template'; // , createFlowsByTemplates
// import SignDialog from '../components/SignDialog';

export default {
  name: 'template',
  components: {
    // SignDialog,
  },
  data() {
    return {
      list: null,
      listLoading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      keyword: '',
      selectedData: [],
      fromPath: '',
      // dialogVisible: false,
      // recipients: [],
    };
  },
  watch: {
    selectedData: {
      handler(newData) {
        this.recipients = newData?.length ? newData?.[0]?.Recipients : [];
      },
      immediate: true,
      deep: true,
    },
  },
  filters: {
    dateFilter(time) {
      return time ? moment(time * 1000).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    templateTypeFilter(type) {
      const typeMap = {
        1: '静默签',
        3: '普通模板',
      };
      return typeMap[type];
    },
    typeFilter(type) {
      const typeMap = {
        0: '待设置',
        1: '劳务派遣合同',
        2: '劳动合同',
        3: '个人合同',
      };
      return typeMap[type];
    },
  },

  created() {
    this.fromPath = this.$route.query?.from;
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.listLoading = true;
      const params = {
        withPreviewUrl: true, // 是否获取模板预览链接
        templateName: this.keyword,
        limit: this.pageSize,
        offset: (this.currentPage - 1) * this.pageSize,
        // QueryAllComponents: false, // 是否返回所有组件信息。默认false，只返回发起方控件；true，返回所有签署方控件
        // ContentType: 0, // 查询内容：0-模板列表及详情（默认），1-仅模板列表
        tenantTemplateType: 0,
      };
      const response = await getTemplateList(params);
      // console.log('getTemplateList====', response);
      if (response.code === 20000 && response?.data?.Templates?.length) {
        this.list = response?.data?.Templates;
        this.listLoading = false;
      } else {
        this.list = [];
        this.listLoading = false;
      }
      this.listLoading = false;
      this.total = response?.data?.TotalCount || 0;
    },

    onChange(value) {
      this.keyword = value;
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    // 新增模板
    addTemplate() {
      this.$router.push({
        path: '/template/detail',
        query: { type: 'add' },
      });
    },

    // 预览
    handleClickInfo(data) {
      if (data?.TemplateId) {
        const tempUrl = data?.PreviewUrl?.replace('test', 'beta');
        // console.log('info====', tempUrl);
        this.$router.push({
          path: '/template/detail',
          query: { templateId: data?.TemplateId, type: 'info', infoUrl: tempUrl },
        });
      }
    },

    // 编辑
    handleClickMod(data) {
      if (data?.TemplateId) {
        this.$router.push({
          path: '/template/detail',
          query: { templateId: data?.TemplateId, type: 'mod' },
        });
      }
    },

    // handleSelectionChange(value) {
    //   console.log('handleSelectionChange====', value);
    //   this.selectedData = [...value];
    // },

    // // 关闭弹框
    // toggleDialog(val) {
    //   this.dialogVisible = val;
    // },

    // // 发起合同按钮点击
    // handleClickCreate(data) {
    //   this.selectedData = [data];
    //   console.log('template====', this.selectedData);
    //   this.dialogVisible = true;
    // },

    // // 处理参数
    // handleFlowInfos(data) {
    //   const curTemplate = this.selectedData?.[0] || {};
    //   const flowInfos = [];
    //   let flowApprovers = [];
    //   // 场景1: BtoC场景 1个C 和 多个C
    //   const organArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'ENTERPRISE');
    //   const organApprover = {
    //     ApproverType: 'ORGANIZATION',
    //     OrganizationName: organArr[0]?.RoleName,
    //     RecipientId: organArr[0]?.RecipientId,
    //   };
    //   const personArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'INDIVIDUAL');
    //   if (data?.persons?.length === 1) {
    //     const usersApprover = {
    //       ApproverType: 'PERSON',
    //       RecipientId: personArr[0]?.RecipientId,
    //       Name: data?.persons?.[0]?.name,
    //       Mobile: data?.persons?.[0]?.mobile,
    //     };
    //     flowApprovers = [organApprover, usersApprover];
    //     flowInfos.push({
    //       FlowName: data?.persons?.[0]?.contractName,
    //       Deadline: this.getAfterOneYearTime(), // 默认是1年有效期 // item?.CreatedOn + (60 * 60 * 24 * 356),
    //       TemplateId: curTemplate?.TemplateId,
    //       FlowApprovers: flowApprovers,
    //     });
    //   } else if (data?.persons?.length > 1) {
    //     data?.persons?.forEach((item) => {
    //       const usersApprover = {
    //         ApproverType: 'PERSON',
    //         RecipientId: personArr[0]?.RecipientId,
    //         Name: item?.name,
    //         Mobile: item?.mobile,
    //       };
    //       flowApprovers = [organApprover, usersApprover];
    //       flowInfos.push({
    //         FlowName: item?.contractName,
    //         Deadline: this.getAfterOneYearTime(), // 默认是1年有效期 // item?.CreatedOn + (60 * 60 * 24 * 356),
    //         TemplateId: curTemplate?.TemplateId,
    //         FlowApprovers: flowApprovers,
    //       });
    //     });
    //   }

    //   return flowInfos;
    // },

    // // 确认 模板发起合同
    // async createByTemplate(data) {
    //   console.log('createByTemplate data', data);
    //   const flowInfos = this.handleFlowInfos(data);
    //   console.log('flowInfos', flowInfos);
    //   const params = {
    //     FlowInfos: flowInfos,
    //     NeedPreview: false, // 是否为预览模式；默认为false，即非预览模式，此时发起合同并返回FlowIds；若为预览模式，不会发起合同，会返回PreviewUrls；
    //     // PreviewType: 1, // 预览链接类型 默认:0-文件流, 1- H5链接 注意:此参数在NeedPreview 为true 时有效,
    //   };
    //   const response = await createFlowsByTemplates(params);
    //   console.log('response===', response);
    //   if (response?.code === 20000) {
    //     this.dialogVisible = false;
    //     this.$message({
    //       message: '创建流程成功',
    //       type: 'success',
    //     });
    //     // 跳转到合同列表页面
    //     this.$router.push({
    //       path: '/contract/list',
    //     });
    //   } else {
    //     this.$message({
    //       message: '创建流程失败',
    //       type: 'warning',
    //     });
    //     this.dialogVisible = false;
    //   }
    // },

    // getAfterOneYearTime() {
    //   return Math.floor((moment().add(1, 'y'))
    //     .utc()
    //     .valueOf() / 1000);
    // },

    // 删除
    // handleClickDelete(data) {
    //   console.log('delete===', data);
    //   if (data?.TemplateId) {
    //     const params = {
    //       OperateType: 'DELETE', // 	操作类型，查询:"SELECT"，删除:"DELETE"，更新:"UPDATE"
    //       TemplateId: data?.TemplateId,
    //     };
    //     operateChannelTemplate(params).then((response) => {
    //       console.log('operateChannelTemplate====', response);
    //     });
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
.template-wrapper {
  padding: 20px;
  .template-search {
    text-align: right;
    margin-bottom: 20px;
    .el-button {
      float: left;
    }
    .el-input {
      width: 400px;
    }
  }
  .template-page {
    position: relative;
    text-align: right;
    margin: 20px 0;
    .el-pagination {
      display: inline-block;
    }
  }
}
</style>
